package com.mazaiting.uac.service.impl;

import com.mazaiting.auth.constant.SecurityConst;
import com.mazaiting.common.core.utils.DateTimeUtil;
import com.mazaiting.common.core.utils.StringUtil;
import com.mazaiting.redis.service.IRedisService;
import com.mazaiting.uac.config.CaptchaProperties;
import com.mazaiting.uac.constant.enums.CaptchaTypeEnum;
import com.mazaiting.uac.domain.vo.CaptchaVO;
import com.mazaiting.uac.service.ICaptchaService;
import com.mazaiting.uac.utils.CaptchaUtil;
import com.wf.captcha.base.Captcha;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 图形验证码实现类
 *
 * @author mazaiting
 * @create_time 2022/9/26 09:32
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ICaptchaServiceImpl implements ICaptchaService {

    private final CaptchaProperties captchaProperties;

    private final IRedisService redisService;

    @Override
    public CaptchaVO get(Long t) {
        long currentTimeMillis = System.currentTimeMillis();
        if (currentTimeMillis - t > captchaProperties.getTimeout()) {
            log.info("当前时间: {}, 获取图形验证码时间: {}",
                    DateTimeUtil.time2String(currentTimeMillis, DateTimeUtil.YYYY_MM_DD_HH_MM_SS_SSS),
                    DateTimeUtil.time2String(t, DateTimeUtil.YYYY_MM_DD_HH_MM_SS_SSS));
            return null;
        }

        // 验证码类型
        CaptchaTypeEnum captchaType = captchaProperties.getType();
        // 生成验证码
        Captcha captcha = CaptchaUtil.getCaptcha(captchaType);
        // 验证码内容
        String captchaValue = captcha.text();
        // 对于数学类型的需要进行处理
        if (captchaType == CaptchaTypeEnum.ARITHMETIC) {
            if (captcha.getCharType() - 1 == CaptchaTypeEnum.ARITHMETIC.ordinal() && captchaValue.contains(".")) {
                captchaValue = captchaValue.split("\\.")[0];
            }
        }

        // 缓存验证码至Redis
        String uuid = StringUtil.getUUID();
        // 缓存验证码
        redisService.set(SecurityConst.VALIDATION_CODE_KEY_PREFIX + uuid, captchaValue, captchaProperties.getTtl(), TimeUnit.SECONDS);

        // 获取到验证码Base64编码字符串
        String captchaBase64 = captcha.toBase64();
        return new CaptchaVO(uuid, captchaBase64);
    }
}
